package com.xhl.controller;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.xhl.service.OrderItemService;
import com.xhl.service.OrderService;
import com.xhl.service.ProductImageService;
import com.xhl.service.ReviewService;
import com.xhl.service.UserService;
import com.xhl.util.DateCode;
import com.xhl.util.SpringContextUtil;
import com.xhl.util.Utils;
import com.xhl.vo.OrderItemVO;
import com.xhl.vo.OrderVO;
import com.xhl.vo.Pager;
import com.xhl.vo.ProductImageVO;
import com.xhl.vo.ResultVO;
import com.xhl.vo.ReviewVO;
import com.xhl.vo.UserVO;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    UserService userService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    ReviewService reviewService;

    @Autowired
    ProductImageService productImageService;

    @GetMapping(value = "/addBuy", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String addBuy(HttpServletRequest request) {
        String uid = request.getParameter("uid");
        String pid = request.getParameter("pid");
        if (uid == null) {
            return "异常";
        }
        OrderItemVO oilist = orderItemService.queryOrderItemById(uid, pid);
        System.out.println(oilist);
        String json = JSON.toJSONString(oilist);
        return json;
    }

    @PostMapping(value = "/shoppingTrolley", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String shoppingTrolley(HttpServletRequest request) {
        String uid = request.getParameter("uid");
        String pid = request.getParameter("pid");
        String num = request.getParameter("num");
        if (uid == null) {
            return "异常";
        }

        OrderItemVO oilist = orderItemService.queryOrderItemById(uid, pid);
        System.out.println(oilist);
        if (oilist == null) {
            OrderItemVO oivo = SpringContextUtil.getBean(OrderItemVO.class);
            oivo.setUid(Integer.valueOf(uid));
            oivo.setPid(Integer.valueOf(pid));
            oivo.setNumber(Integer.valueOf(num));
            System.out.println(oivo);
            orderItemService.shoppingTrolley(oivo);
        } else {
            //说明有该商品增加数量
            orderItemService.updateOrderItemById(oilist.getOiid(), num);
        }

        String json = JSON.toJSONString("成功加入购物车");
        return json;
    }


    @PostMapping(value = "/addOrder", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String addOrder(HttpServletRequest request) {
        String oiids = request.getParameter("oiids");
        if (oiids == null) {
            return "";
        }
        @SuppressWarnings("unchecked")
        ResultVO<Long> rvo = SpringContextUtil.getBean(ResultVO.class);
        if (oiids == null || oiids == "") {
            rvo.setCode("199");
            rvo.setMsg("订单失效");
            String json = JSON.toJSONString(rvo);
            return json;
        }

        String[] oiidArr = oiids.split("/");

        String address = request.getParameter("address");
        String post = request.getParameter("post");
        String receiver = request.getParameter("receiver");
        String mobile = request.getParameter("mobile");
        String userMessage = request.getParameter("userMessage");
        String uid = request.getParameter("uid");

        OrderVO ovo = SpringContextUtil.getBean(OrderVO.class);

        ovo.setOrderCode(DateCode.setCode());
        ovo.setAddress(address);
        ovo.setPost(post);
        ovo.setReceiver(receiver);
        ovo.setMobile(mobile);
        ovo.setUserMessage(userMessage);
        ovo.setUid(Integer.valueOf(uid));
        ovo.setStatus("waitPay");

        System.out.println("ovo = " + ovo);

        orderService.addOrder(ovo);    //增加订单

        long maxId = orderService.orderMaxId();    //新增id

        for (String oiid : oiidArr) {    //订单下商品oiid
            orderItemService.updateOid(maxId + "", oiid);
        }

        rvo.setMsg("下单成功");
        rvo.setCode("200");
        rvo.setBody(maxId);
        String json = JSON.toJSONString(rvo);
        return json;
    }

    @GetMapping(value = "/placeAnOrder", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String PlaceAnOrder(HttpServletRequest request) {
        String oiids = request.getParameter("oiids");
        if (oiids == null) {
            return "异常";
        }
        System.out.println(oiids + "-----------");
        String[] oiidArr = oiids.split("/");
        List<OrderItemVO> oilist = new ArrayList<>();
        for (String oiid : oiidArr) {
            System.out.println(oiid + " length" + oiidArr.length);
            OrderItemVO oivo = orderItemService.queryOrderItemOiid(oiid);
            oilist.add(oivo);
        }

        String json = JSON.toJSONString(oilist);
        return json;
    }

    @GetMapping(value = "/updateOrderItem", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String updateOrderItem(HttpServletRequest request) {
        String oiid = request.getParameter("oiid");
        if (oiid == null) {
            return "异常";
        }
        String number = request.getParameter("number");
        orderItemService.updateOrderItem(oiid, number);
        String json = JSON.toJSONString("修改成功");
        return json;
    }

    @GetMapping(value = "/deleteOrderItem", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String deleteOrderItem(HttpServletRequest request) {
        String oiid = request.getParameter("oiid");
        if (oiid == null) {
            return "异常";
        }
        System.out.println(oiid);
        orderItemService.deleteOrderItem(oiid);
        String json = JSON.toJSONString("删除成功--");
        return json;
    }

    @GetMapping(value = "/queryOrderItemInfo", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String queryOrderItemInfo(HttpServletRequest request) {
        String uid = request.getParameter("uid");
        if (uid == null) {
            return "异常";
        }
        List<OrderItemVO> oivo = orderItemService.queryOrderItemInfo(uid);
        String json = JSON.toJSONString(oivo);
        return json;
    }

    /*
     * 订单查询详情
     */
    // produces = "text/html;charset=UTF-8"
    @RequestMapping(value = "/queryOrderItemId", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String queryOrderItemId(HttpServletRequest request, HttpServletResponse response) {

        String oiid = request.getParameter("oiid");
        System.out.println(oiid);
        if (oiid == null) {
            return "异常";
        }
        OrderItemVO oivo = orderItemService.queryOrderItemOiid(oiid);
        System.out.println(oivo);

        Long orderSum = orderItemService.queryNumberSum(oivo.getPid() + "");
        System.out.println(orderSum + "近30天数");

        oivo.setOrderSum((orderSum == null ? 0 : orderSum));

        Long reviewSum = reviewService.queryReviewSum(oivo.getPid() + "");
        System.out.println(reviewSum + " 留言数");

        oivo.setReviewSum(reviewSum);

        String json = JSON.toJSONString(oivo);
        return json;
    }


    @PostMapping(value = "/addComment", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String addComment(HttpServletRequest request) {
        String oid = request.getParameter("oid");
        if (oid == null) {
            return "异常";
        }
        orderService.orderAccomplish(oid);//订单完成

        String uid = request.getParameter("uid");
        String pid = request.getParameter("pid");
        String content = request.getParameter("content");
        ReviewVO rvo = SpringContextUtil.getBean(ReviewVO.class);
        rvo.setUid(Integer.valueOf(uid));
        rvo.setPid(Integer.valueOf(pid));
        rvo.setContent(content);
        System.out.println(oid + "  " + uid + " " + pid);

        reviewService.addComment(rvo); //添加评论

        List<ReviewVO> rlist = reviewService.queryReviewPid(pid);

        @SuppressWarnings("unchecked")
        ResultVO<List<ReviewVO>> revo = SpringContextUtil.getBean(ResultVO.class);

        revo.setBody(rlist);
        revo.setCode("200");
        revo.setMsg("感谢您对我们做出的评论，我们会更加努力！！");

        String json = JSON.toJSONString(revo);
        return json;
    }


    @GetMapping(value = "/address", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String address(HttpServletRequest request) {
        String oid = request.getParameter("oid");
        if (oid == null) {
            return "异常";
        }
        OrderVO ovo = orderService.queryOrderOid(oid);
        // 发货
        orderService.waitDelivery(oid);
        String json = JSON.toJSONString(ovo);
        return json;
    }

    /*
     * 订单收货confirm receipt
     */
    @GetMapping(value = "/confirmReceipt", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String confirmReceipt(HttpServletRequest request) {
        String oid = request.getParameter("oid");
        if (oid == null) {
            return "异常";
        }
        orderService.confirmReceipt(oid);
        return "交易已经成功，卖家将收到您的货款。";
    }

    /*
     * 订单发货
     */
    @GetMapping(value = "/queryByType", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String queryByType(HttpServletRequest request) {
        String uid = request.getParameter("uid");
        if (uid == null) {
            return "异常";
        }
        String orderType = request.getParameter("orderType");
        if (orderType.equals("all")) {
            List<OrderVO> olist = orderService.queryOrderById(uid, null);

            String json = JSON.toJSONString(fullOrderInfo(olist));
            return json;
        }
        List<OrderVO> olist = orderService.queryOrderById(uid, orderType);

        String json = JSON.toJSONString(fullOrderInfo(olist));
        return json;
    }

    public List<OrderVO> fullOrderInfo(List<OrderVO> olist) {
        for (OrderVO orderVO : olist) {
            UserVO uvo = userService.queryUserId(orderVO.getUid());
            orderVO.setUser(uvo);
            List<OrderItemVO> oilist = orderItemService.queryOrderItemId(orderVO.getOid() + "");
            orderVO.setOilist(oilist);
            for (OrderItemVO oi : orderVO.getOilist()) {
                int sum = oi.getNumber();
                orderVO.setNumber(orderVO.getNumber() + sum);
                Double num = orderVO.getTotalValue() + (oi.getProduct().getPromotePrice() * sum);
                DecimalFormat df = new DecimalFormat("#.00");
                orderVO.setTotalValue(Double.valueOf(df.format(num)));
            }
        }
        return olist;
    }

    // 图片显示
    @RequestMapping("/getImageSingle")
    @ResponseBody
    public void getSingle(HttpServletRequest rq, HttpServletResponse rp) {
        String pid = rq.getParameter("pid");
        if (pid == null) {
            return;
        }
        List<ProductImageVO> pilist = productImageService.queryProductImage(pid, "type_single");
        if (pilist.isEmpty()) {
            return;
        }
        ProductImageVO pivo = Utils.getLastElement(pilist);
        String filePath = "D:\\img\\productSingle\\" + pivo.getPiid() + ".jpg";
        Utils.showImg(rp, filePath);

    }

    /*
     * 订单查询
     */
    // produces = "text/html;charset=UTF-8"
    @RequestMapping(value = "/query", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String queryOrder(HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException {

        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        if (pageNum == null) {
            return "异常";
        }

        @SuppressWarnings("unchecked")
        Pager<OrderVO> p = SpringContextUtil.getBean(Pager.class);

        p.setSize(Integer.valueOf(pageSize));
        p.setPage((Integer.valueOf(pageNum) - 1) * Integer.valueOf(pageSize));

        List<OrderVO> olist = orderService.queryOrderInfo(p);

        long count = orderService.count();

        p.setTotal(count);
        p.setRows(fullOrderInfo(olist));
        String json = JSON.toJSONString(p);
        // String ps = new String(json.getBytes("iso-8859-1"), "UTF-8");
        return json;
    }

    /*
     * 订单发货
     */
    @GetMapping(value = "/shipments", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void orderShipments(HttpServletRequest request) {
        String oid = request.getParameter("oid");
        if (oid == null) {
            return;
        }

        orderService.orderUpdateShipments(oid);
        System.out.println(oid + " 发货成功");
    }
}
